package com.scs.application.core.excel.handler;

import cn.afterturn.easypoi.handler.inter.IExcelDictHandler;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.global.GlobalDictService;
import com.scs.application.core.utils.CacheUtils;
import com.scs.application.core.utils.SpringHolder;
import com.scs.application.modules.upms.entity.DictData;

import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Description: excel 字典处理类
 */
public class ExcelDictHandlerImpl implements IExcelDictHandler {

    private ExcelDictHandlerImpl() {
    }

    private volatile static ExcelDictHandlerImpl INSTANCE;

    public static ExcelDictHandlerImpl getInstance() {
        if (INSTANCE == null) {
            synchronized (ExcelDictHandlerImpl.class) {
                INSTANCE = new ExcelDictHandlerImpl();
            }
        }
        return INSTANCE;
    }

    @Override
    public String toName(String dict, Object obj, String name, Object value) {
        List<DictData> dictDataList = getDictData(dict);
        AtomicReference<String> labelRet = new AtomicReference<>();
        dictDataList.stream().filter(tmp -> tmp.getLabel().equals(name) || tmp.getValue().equals(value+"")).findFirst().ifPresent( one -> {
            labelRet.set(one.getLabel());
        });
        BusinessException.throwErrorIf(labelRet == null ,"数据字典未找到");
        return labelRet.get();
    }

    @Override
    public String toValue(String dict, Object obj, String name, Object value) {
        List<DictData> dictDataList = getDictData(dict);
        AtomicReference<String> valueRet  = new AtomicReference<>();
        dictDataList.stream().filter(tmp -> tmp.getLabel().equals(value) || tmp.getValue().equals(value+"")).findFirst().ifPresent( one -> {
            valueRet.set(one.getValue());
        });
        BusinessException.throwErrorIf(valueRet == null ,"数据字典未找到");
        return valueRet.get();
    }

    private GlobalDictService getGlobalDictService() {
        try {
            return SpringHolder.getBean(GlobalDictService.class);
        } catch (Exception e) {
            return null;
        }
    }

    private List<DictData> getDictData(String dict) {
        List<DictData> dictDataList = (List<DictData>) CacheUtils.get(CacheUtils.SYS_CACHE,dict);
        BusinessException.throwErrorIf(dictDataList == null || dictDataList.isEmpty() ,"数据字典未找到");
        return dictDataList;
    }


}

